#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2015  Data Enlighten Technology (Beijing) Co.,Ltd


import base64
import re
from mj_parser import common_errors
import Lib.Logger.log4py as logging

'''
    def parser_html_bmw(self, file_name):
        result_list = self.get_default_result()
        b = common_errors.ERR_SUCCESS
        try:
            fobj = open(file_name, encoding='utf_8_sig')
            html = fobj.read()
            b = common_errors.ERR_SUCCESS

            if html.find('没有找到您搜索的车辆识别代码的数据。该车辆识别代码不存在或者尚未输入相关车辆数据') >= 0:
                b = common_errors.ERR_NO_VIN
                return b, result_list
            result_list['mospid'] = self.find_template_value(html, 'mospid')
            result_list['upds'] = self.find_template_value(html, 'upds')

            p = re.compile('<h2>标准设备</h2></td></tr></thead><tbody>.+?</tbody>', re.S)
            html_div_chn_li = p.findall(html)

            sa_list = []
            li = []
            if html_div_chn_li is not None and len(html_div_chn_li) > 0:

                p = re.compile('<tr><td>.+?</td>', re.S)
                model_li = p.findall(html_div_chn_li[0])
                for x in model_li:
                    x = x.replace('<tr><td>', '').replace('</td>', '').replace('\t', '').replace('\n', '')
                    li.append(x)
                sa_list += li
            p = re.compile('<h2>专用附件</h2></td></tr></thead><tbody>.+?</tbody>', re.S)
            html_div_chn_li = p.findall(html)

            if html_div_chn_li is not None and len(html_div_chn_li) > 0:
                li = []
                p = re.compile('<tr><td>.+?</td>', re.S)
                model_li = p.findall(html_div_chn_li[0])
                for x in model_li:
                    x = x.replace('<tr><td>', '').replace('</td>', '').replace('\t', '').replace('\n', '')
                    li.append(x)
                sa_list += li
            if len(li) > 0:
                result_list['pr_list'] = '|'.join(sa_list)
            else:
                result_list['pr_list'] = ''

        except Exception as ex:
            print(ex)
        return b, result_list
'''


class AudiParserWeb:
    default_result = {
        'model': '',
        'year': '',
        'manufacture_date': '',
        'type': '',
        'engine': '',
        'transmission': '',
        'body': '',
        'setting': '',
        'inner_color': '',
        'color': '',
        'manufacturer': '',
        'production_code': '',
        'engine_number': '',
        'country_symbol': '',
        'content': '',
        'brand': '',
        'pr_list': '',
        'raw_content': ''
    }

    def __init__(self, root_dir):
        self.root_dir = root_dir
        self.logger = logging.get_logger("crawler", "AudiParserWeb")

    def find_string(self, html, name):
        p = re.compile('<th>' + name + '</th><td colspan="2">.+?</tr>', re.S)
        html_div_chn_li = p.findall(html)
        if html_div_chn_li is not None and len(html_div_chn_li) > 0:
            return html_div_chn_li[0].replace('<th>' + name + '</th><td colspan="2">', '').replace('</tr>', '').replace(
                '</td>', '').replace('\t', '').replace('\n', '').replace('&nbsp;', '').replace('\xa0', '')
        else:
            return ''

    def find_template_value(self, html, name):
        p = re.compile('"' + name + '":.+?,', re.S)
        html_div_chn_li = p.findall(html)
        if html_div_chn_li is not None and len(html_div_chn_li) > 0:
            return html_div_chn_li[0].replace('"' + name + '":', '').replace(',', '')
        else:
            return ''

    def parse(self, file_name):
        b = common_errors.ERR_SUCCESS
        result_list = self.get_default_result()
        try:
            fobj = open(file_name, encoding='utf_8_sig')
            html = fobj.read()

            if html.find('没有找到您搜索的车辆识别代码的数据。该车辆识别代码不存在或者尚未输入相关车辆数据') >= 0:
                b = common_errors.ERR_NO_VIN
                return b, result_list

            # 车型特殊处理
            tempstr = self.find_string(html, '机型')
            model_format_string = self.find_string(html, '车型') if len(tempstr) == 0 else tempstr

            p = re.compile('<span style="font-weight: normal;">.+? </span>', re.S)
            model_li = p.findall(model_format_string)
            if model_li is not None and len(model_li) > 0:
                result_list['model'] = model_li[0].replace('<span style="font-weight: normal;">', '').replace('</span>',
                                                                                                              '')
            else:
                result_list['model'] = ''

            result_list['year'] = self.find_string(html, '车型年份')
            result_list['manufacture_date'] = self.find_string(html, '生产日期')
            result_list['type'] = self.find_string(html, '销售类型')
            result_list['engine'] = self.find_string(html, '发动机代码')
            result_list['transmission'] = self.find_string(html, '变速器代码')
            result_list['body'] = self.find_string(html, '前后桥标识')
            result_list['setting'] = self.find_string(html, '配置')
            result_list['inner_color'] = self.find_string(html, '顶部颜色')
            result_list['color'] = self.find_string(html, '外观颜色 / 油漆号')

            result_list['manufacturer'] = ''
            result_list['production_code'] = ''
            result_list['engine_number'] = ''
            result_list['country_symbol'] = ''
            result_list['content'] = self.find_template_value(html, 'episType')
            result_list['brand'] = ''
            result_list['raw_content'] = base64.b64encode(html.encode('utf-8')).decode('utf-8')
            p = re.compile('<td class="prCode">.+?</td>', re.S)
            html_div_chn_li = p.findall(html)

            if html_div_chn_li is not None and len(html_div_chn_li) > 0:
                li = []
                for x in html_div_chn_li:
                    x = x.replace('<td class="prCode">', '').replace('</td>', '').replace('\t', '').replace('\n', '')
                    li.append(x)
                result_list['pr_list'] = '|'.join(li)
            else:
                result_list['pr_list'] = ''
                b = common_errors.ERR_NO_CONTENT
                self.logger.warning('pr_list is empty.')

        except Exception as ex:
            self.logger.error(ex)
            b = common_errors.ERR_UNKNOWN

        return b, result_list

    def get_default_result(self):
        return AudiParserWeb.default_result.copy()


if __name__ == '__main__':
    per = AudiParserWeb('.\\')
    print(111)
    per.parse('C:\\Users\\Louyj\\Desktop\\tmp\\LFV3A24G8E3028592.html')